import axios from 'axios';
import {getToken, removeToken} from './auth';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router'
import JSONBIG from 'json-bigint'
import {useUserStore} from '@/store'
axios.defaults.transformResponse = [
    function (data){
        const json = JSONBIG({
            storeAsString: true
        })
        const res = json.parse(data)
        return res
    }
]
const instance = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 15000,
    withCredentials: true
})

instance.interceptors.request.use(function (config) {
    if(getToken()){
        config.headers['token'] = getToken()
    }
    return config;
})

instance.interceptors.response.use(function (response) {
    // token无效
    if(response.data.code == "50000"){
        ElMessage.error("用户登录过期，请重新登录")
        removeToken()
        useUserStore().reset()
        window.location.reload()
        // useRouter().push('/login')
    }
    return response;
}, function (error) {
    ElMessage.error("网络不佳，请稍后再试")
    return Promise.reject(error);
});

export default instance
